#!/bin/bash

#function usage
usage()
{
  echo "usage: mkoobc [src_dir] [src_class] [tgt_dir] [tgt_class]"
  exit 1
}

if [ -n "$1" ]; then
  SRC_DIR=$1
  echo "SRC_DIR=\"$SRC_DIR\""
else
  echo "source dir missing"
  usage
fi

if [ -n "$2" ]; then
  SRC_CLASS=$2
  echo "SRC_CLASS=\"$SRC_CLASS\""
else
  echo "source class missing"
  usage
fi

if [ -n "$3" ]; then
  TGT_DIR=$3
  echo "TGT_DIR=\"$TGT_DIR\""
else
  echo "target dir missing"
  usage
fi

if [ -n "$4" ]; then
  TGT_CLASS=$4
  echo "TGT_CLASS=\"$TGT_CLASS\""
else
  echo "target class missing"
  usage
fi


if [ -d "$SRC_DIR" ]; then
  if [ -d "$TGT_DIR" ]; then
    echo "The dir \"$TGT_DIR\" already exists"
  else
    # make general dir and files of the
    mkdir $TGT_DIR
    mkdir ${TGT_DIR}/src
    mkdir ${TGT_DIR}/include
    mkdir ${TGT_DIR}/tests
    cp ${SRC_DIR}/tests/makefile ${TGT_DIR}/tests/.
  fi

  #copy files of the target class 
  sed "s/${SRC_CLASS}/${TGT_CLASS}/g" ${SRC_DIR}/include/${SRC_CLASS}.h > ${TGT_DIR}/include/${TGT_CLASS}.h
  sed "s/${SRC_CLASS}/${TGT_CLASS}/g" ${SRC_DIR}/src/${SRC_CLASS}.cc > ${TGT_DIR}/src/${TGT_CLASS}.cc
  mkdir ${TGT_DIR}/tests/${TGT_CLASS}
  cp ${SRC_DIR}/tests/${SRC_CLASS}/Makefile ${TGT_DIR}/tests/${TGT_CLASS}/Makefile
  sed "s/${SRC_CLASS}/${TGT_CLASS}/g" ${SRC_DIR}/tests/${SRC_CLASS}/Test${SRC_CLASS}.h > ${TGT_DIR}/tests/${TGT_CLASS}/Test${TGT_CLASS}.h
  declare -u TMP_SRC=$SRC_CLASS
  declare -u TMP_TGT=$TGT_CLASS
  sed "s/${TMP_SRC}/${TMP_TGT}/g" ${TGT_DIR}/include/${TGT_CLASS}.h > ${TGT_DIR}/include/${TGT_CLASS}_1.h
  mv ${TGT_DIR}/include/${TGT_CLASS}_1.h ${TGT_DIR}/include/${TGT_CLASS}.h

  declare -l TMP_SRC=$SRC_CLASS
  declare -l TMP_TGT=$TGT_CLASS
  sed "s/${TMP_SRC}/${TMP_TGT}/g" ${TGT_DIR}/tests/${TGT_CLASS}/Test${TGT_CLASS}.h > ${TGT_DIR}/tests/${TGT_CLASS}/Test${TGT_CLASS}_1.h
  mv ${TGT_DIR}/tests/${TGT_CLASS}/Test${TGT_CLASS}_1.h ${TGT_DIR}/tests/${TGT_CLASS}/Test${TGT_CLASS}.h

else
  echo "source dir \"$SRC_DIR\" doesn't exist !"
  exit 1
fi
